
import request from '@/utils/request'

export default class OSSClient {
  client = null
  host = ''
  constructor() {
    this.init()
  }
  loadCDN () {
    if (document.querySelector('#oss-cdn')) return;
    const src = 'https://gosspublic.alicdn.com/aliyun-oss-sdk-6.15.0.min.js'
    const dom = window.document.createElement('script')
    dom.id = 'oss-cdn'
    dom.type = "text/javascript";
    dom.src = src;
    document.getElementsByTagName('head')[0].append(dom)
    return new Promise((r) => {
      dom.onload = () => {
        r()
      }
    })
  }
  async init () {
    await this.loadCDN()
    // const [res] = await Promise.all([
    //   request('/file/ossSts/'),
    //   this.loadCDN()
    // ])

    let config = 
    process.env.VUE_APP_OSS==='production'?
    {
      accessKeyId: 'LTAI5tBXzfPVjgsM4wa8YKcE',
      accessKeySecret: 'z2TKwMSvATJuQnPDxexixvfgd40ptJ',
      region: 'oss-cn-hongkong',
      bucket: 'prod-hk-loan',
      secure: true
    }:
    {
      accessKeyId: 'LTAI5tBXzfPVjgsM4wa8YKcE',
      accessKeySecret: 'z2TKwMSvATJuQnPDxexixvfgd40ptJ',
      region: 'oss-cn-hongkong',
      bucket: 'test-hk-loan',
      secure: true
    }
    this.client = new OSS(config);
    this.host = 'https://' + config.bucket + '.' + this.client.options.endpoint.host + '/'
  }
  async __upload (filePath, file) {
    let result = await this.client.put(filePath, file)
    return result
  }
  async upload (file, type, projectId, relationId) {
    try {
      let key = `${projectId}/${type}/`
      if (relationId) { key += `${relationId}/` }
      key += file.name
      await this.__upload(key, file)
      return this.host + key
    } catch (err) {
      throw err
    }
  }
}